package org.alino.core.utils;

import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Desc TODO
 * @Author by Brant
 * @Date 2016/12/23
 */
public class DateUtils {
    /**
     *
     * @param strDate
     * @return
     */
    public static Date parseDate(String strDate) {
        return parseDate(strDate, null);
    }

    /**
     * parseDate
     *
     * @param strDate
     * @param pattern
     * @return
     */
    public static Date parseDate(String strDate, String pattern) {
        Date date = null;
        try {
            if(pattern == null) {
                pattern = YYYYMMDD;
            }
            SimpleDateFormat format = new SimpleDateFormat(pattern);
            date = format.parse(strDate);
        } catch (Exception e) {
        }
        return date;
    }

    /**
     * 格式化日期
     *
     * @param date
     * @param pattern
     * @return
     */
    public static String formatDate(Date date, String pattern) {
        if(null == date)
            return null;
        SimpleDateFormat dateFormator = new SimpleDateFormat(pattern);
        return dateFormator.format(date);
    }

    public static String GetAddDate(String StrDate, int year, int month, int day){
        return GetSysDate(YYYYMMDD,StrDate,year,month,day);
    }
    public static String GetSysDate(String format, String StrDate, int year, int month, int day) {
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sFmt = new SimpleDateFormat(format);
        cal.setTime(sFmt.parse((StrDate), new ParsePosition(0)));
        if (day != 0) {
            cal.add(cal.DATE, day);
        }
        if (month != 0) {
            cal.add(cal.MONTH, month);
        }
        if (year != 0) {
            cal.add(cal.YEAR, year);
        }
        return sFmt.format(cal.getTime());
    }

    public static String formatDate(String dateStr, String pattern) {
        Date date = parseDate(dateStr,pattern);
        if(null == date)
            return null;
        SimpleDateFormat dateFormator = new SimpleDateFormat(pattern);
        return dateFormator.format(date);
    }

    public static String formatDateTimeMillis(Long millis, String pattern) {
        SimpleDateFormat dateFormator = new SimpleDateFormat(pattern);
        return dateFormator.format(formatDateTimeMillis(millis));
    }

    public static String timeIntervalByHourAndMinute(Long highMillis, Long lowMillis) {

        int h = (int)Math.floor((highMillis-lowMillis)/(1000*60*60));
        int m = (int)Math.floor(((highMillis-lowMillis)-h*1000*60*60)/(1000*60));
        String str = "";
        if(h>0) str =  h+"小时 ";
        str += m + "分钟";

        return str;
    }

    public static Date formatDateTimeMillis(long millis) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(millis);
        return calendar.getTime();
    }

    /**
     * 获得系统的当前时间，毫秒.
     *
     * @return long
     */
    public static long getCurrentTimeMillis() {
        return System.currentTimeMillis();
    }

    /**
     * 获得当前系统时间
     *
     * @param pattern
     * @return
     */
    public static String getCurrentDateTime(String pattern) {

        Date currentDate = new Date();
        SimpleDateFormat dateFormator = new SimpleDateFormat(pattern);

        return dateFormator.format(currentDate);
    }

    /**
     * 获取指定日期的年份
     *
     * @param date
     * @return
     */
    public static int getYear(Date date) {

        if(null == date)
            return -1;
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);

        return calendar.get(Calendar.YEAR);
    }

    /**
     * 获取指定日期的年份
     *
     * @param millis
     * @return
     */
    public static int getYear(long millis) {

        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(millis);

        return calendar.get(Calendar.YEAR);
    }

    /**
     * 获取指定日期的月份
     *
     * @param date
     * @return
     */
    public static int getMonth(Date date) {

        if(null == date)
            return -1;
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);

        return (calendar.get(Calendar.MONTH) + 1);
    }

    /**
     * 获取指定日期的月份
     *
     * @param millis
     * @return
     */
    public static int getMonth(long millis) {

        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(millis);

        return (calendar.get(Calendar.MONTH) + 1);
    }

    /**
     * 获取指定的日期的日(月份中的天数)
     *
     * @param date
     * @return
     */
    public static int getDay(Date date) {

        if(null == date)
            return -1;
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);

        return calendar.get(Calendar.DAY_OF_MONTH);
    }

    /**
     * 获取指定的日期的日(月份中的天数)
     *
     * @param millis
     * @return
     */
    public static int getDay(long millis) {

        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(millis);

        return calendar.get(Calendar.DAY_OF_MONTH);
    }

    /**
     * 获取指定的日期的日(年份中的天数)
     *
     * @param date
     * @return
     */
    public static int getDayOfYear(Date date) {

        if(null == date)
            return -1;
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);

        return calendar.get(Calendar.DAY_OF_YEAR);
    }

    /**
     * 获取指定的日期的日(年中的天数)
     *
     * @param millis
     * @return
     */
    public static int getDayOfYear(long millis) {

        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(millis);

        return calendar.get(Calendar.DAY_OF_YEAR);
    }

    /**
     * 获取指定年份的第一天（年中的天数）
     *
     * @param year
     * @return
     */
    public static int getMinDayOfYear(int year){

        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, year);

        return calendar.getActualMinimum(Calendar.DAY_OF_YEAR);
    }

    /**
     * 获取指定年份的最后一天（年中的天数）
     *
     * @param year
     * @return
     */
    public static int getMaxDayOfYear(int year){

        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, year);

        return calendar.getActualMaximum(Calendar.DAY_OF_YEAR);
    }
    /**
     * 获取当前年份
     * @return
     */
    public static int getCurrentYear() {
        Calendar calendar = Calendar.getInstance();
        return calendar.get(Calendar.YEAR);
    }


    /**
     * 计算两个时间段内的天数
     * @param startDate
     * @param endDate
     * @return
     */
    public static int getDayCountBetweenDate(Date startDate, Date endDate){

        if(null == startDate || null == endDate){

            return 0;
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        if(sdf.format(startDate).compareTo(sdf.format(endDate))>=0){

            return 0;
        }
        int count = 0;
        Calendar c = Calendar.getInstance();

        c.setTime(endDate);
        int ed = c.get(Calendar.DAY_OF_YEAR);
        int ey = c.get(Calendar.YEAR);

        c.setTime(startDate);
        int sy = c.get(Calendar.YEAR);
        int sd = c.get(Calendar.DAY_OF_YEAR);

        // 计算间隔的整年天数
        int yearIntervalDays = 0;
        for(int i=1; i< ey - sy; i++){
            c.set(Calendar.YEAR, sy + i);
            yearIntervalDays += c.getActualMaximum(Calendar.DAY_OF_YEAR);
        }

        if(ey > sy){ // 处理跨年
            c.setTime(startDate);
            int sDays = c.getActualMaximum(Calendar.DAY_OF_YEAR) - c.get(Calendar.DAY_OF_YEAR);

            c.setTime(endDate);
            int eDays = c.get(Calendar.DAY_OF_YEAR);

            count = yearIntervalDays + sDays + eDays;
        }else
            count = ed - sd;

        return count;
    }

    /**
     * 计算两个时间段内的天数
     * @param startDateMillis
     * @param endDateMillis
     * @return
     */
    public static int getDayCountBetweenDate(long startDateMillis, long endDateMillis){

        if(0 == startDateMillis || 0 == endDateMillis){

            return 0;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(startDateMillis);
        Date startDate = calendar.getTime();

        calendar.setTimeInMillis(endDateMillis);
        Date endDate = calendar.getTime();

        return getDayCountBetweenDate(startDate, endDate);
    }


    // 一年的毫秒数
    public final static long YEAR_MILLIS = 24L*60*60*365*1000;
    public final static long MONTH_MILLIS = 24L*60*60*30*1000;
    public final static long WEEK_MILLIS = 24L*60*60*7*1000;
    public final static long YESTERDAY_MILLIS = 24L*60*60*1000*2;
    public final static long DAY_MILLIS = 24L*60*60*1000;
    public final static long HOUR_MILLIS = 60L*60*1000;
    public final static long MINUTE_MILLIS = 60L*1000;
    public final static long SECOND_MILLIS = 1000L;

    public final static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";
    public final static String YYYYMMDD_HHMM = "yyyy.MM.dd HH:mm";
    public final static String YYYY_MM_DD_CHINA = "yyyy年MM月dd日";
    public final static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
    public final static String YYYY_MM_DD = "yyyy-MM-dd";
    public final static String YYYYMMDD = "yyyyMMdd";
    public final static String YYYYMM = "yyyyMM";
    public final static String YYYY_MM_DD_HH_MM = "yyyy-MM-dd HH:mm";
    public final static String YY_MM_DD_HH_MM = "yy-MM-dd HH:mm";
    public final static String MM_DD_HH_MM = "MM-dd HH:mm";
    public final static String HH_MM = "HH:mm";

    /**
     * 比较两个时间的大小
     * @param startDate
     * @param endDate
     * startDate >= endDate return true else return false
     * @return
     */
    public static boolean compareDate(Date startDate, Date endDate) {
        if (startDate == null || endDate == null) {
            return true;
        }
        return (endDate.getTime()-startDate.getTime()) >= 0 ? true : false;
    }

    public static boolean compareDate(long start, long end) {
        if (start <= 0 || end <= 0) {
            return true;
        }
        return (start-end) >= 0 ? true : false;
    }
    /**
     * 比较两个时间的大小（按天数）
     *
     * @param startDate
     * @param endDate
     * @return
     */
    public static int compareDateByDays(Date startDate, Date endDate) {
        if (startDate == null || endDate == null) {
            return 0;
        }
        String startDateStr = formatDate(startDate, YYYY_MM_DD);
        String endDateStr = formatDate(endDate, YYYY_MM_DD);

        return startDateStr.compareTo(endDateStr);
    }

    public static int compareDateByDays(long start, long end) {
        if (start <= 0 || end <= 0) {
            return 0;
        }
        String startDateStr = formatDateTimeMillis(start, YYYY_MM_DD);
        String endDateStr = formatDateTimeMillis(end, YYYY_MM_DD);

        return startDateStr.compareTo(endDateStr);
    }

    public static boolean exec(String s) {
        Pattern pattern = Pattern.compile("(d{4})-d{2}-d{2}");
        Matcher matcher = pattern.matcher(s);
        if (matcher.find()){
            return true;
        }else {
            return false;
        }
    }

    public static void main(String[] args) throws ParseException {
        System.out.println(exec("2015-06-06"));
        //System.out.println(formatDate(getDateBeforeOrAfterYears(new Date(),-1),YYYYMMDD));
        /*List<String> months = getMonthBetween("20150901","20180301");
        for(String month:months){
            System.out.println(month);
        }*/
        //System.out.println(checkDateFormat("201609021",YYYYMMDD));
    }

    public static boolean checkDateFormat(String date,String pattern){
        SimpleDateFormat format=new SimpleDateFormat(pattern);
        boolean dateflag = true;
        try{
            Date dates = format.parse(date);
        } catch (ParseException e) {
            dateflag=false;
        }
        return dateflag;
    }

    public static List<String> getMonthBetween(String minDate, String maxDate){
        ArrayList<String> result = new ArrayList<String>();
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");//格式化为年月
            Calendar min = Calendar.getInstance();
            Calendar max = Calendar.getInstance();
            min.setTime(sdf.parse(minDate));
            min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1);
            max.setTime(sdf.parse(maxDate));
            max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2);
            Calendar curr = min;
            while (curr.before(max)) {
                result.add(sdf.format(curr.getTime()));
                curr.add(Calendar.MONTH, 1);
            }
        }catch (ParseException e) {
            e.printStackTrace();
        }
        return result;
    }



    /**
     * 计算出date day天之前或之后的日期
     *
     * @param date 日期
     * @param date 天数，正数为向后几天，负数为向前几天
     * @return 返回Date日期类型
     */
    public static Date getDateBeforeOrAfterDays(Date date, int days) {
        Calendar now = Calendar.getInstance();
        now.setTime(date);
        now.set(Calendar.DATE, now.get(Calendar.DATE) + days);
        return now.getTime();
    }

    /**
     * 计算出date monthes月之前或之后的日期
     *
     * @param date    日期
     * @param monthes 月数，正数为向后几天，负数为向前几天
     * @return 返回Date日期类型
     */
    public static Date getDateBeforeOrAfterMonthes(Date date, int monthes) {
        Calendar now = Calendar.getInstance();
        now.setTime(date);
        now.set(Calendar.MONTH, now.get(Calendar.MONTH) + monthes);
        return now.getTime();
    }

    /**
     * 计算出date years年之前或之后的日期
     *
     * @param date  日期
     * @param years 年数，正数为向后几天，负数为向前几天
     * @return 返回Date日期类型
     */
    public static Date getDateBeforeOrAfterYears(Date date, int years) {
        Calendar now = Calendar.getInstance();
        now.setTime(date);
        now.set(Calendar.YEAR, now.get(Calendar.YEAR) + years);
        return now.getTime();
    }
    /**
     * 返回某月的开始时间
     * @param date
     * @return
     */
    public static Date getFirstDateOfMonth(Date date) {
        if (null == date) {
            return null;
        }
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.set(Calendar.DAY_OF_MONTH,c.getActualMinimum(Calendar.DAY_OF_MONTH));
        return c.getTime();
    }
    /**
     * 返回某月的结束时间
     * @param date
     * @return
     */
    public static Date getLastDateOfMonth(Date date) {
        if (null == date) {
            return null;
        }
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.set(Calendar.DAY_OF_MONTH,c.getActualMaximum(Calendar.DAY_OF_MONTH));
        c.set(Calendar.HOUR_OF_DAY, 23);
        c.set(Calendar.SECOND, 59);
        c.set(Calendar.MINUTE, 59);
        return c.getTime();
    }
    /**
     * 返回某天的开始时间
     * @param date
     * @return
     */
    public static Date begin(Date date) {
        if (null == date) {
            return null;
        }
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.set(Calendar.HOUR_OF_DAY,0);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MINUTE, 0);
        return c.getTime();
    }
    /**
     * 返回某天的结束时间
     * @param date
     * @return
     */
    public static Date end(Date date) {
        if (null == date) {
            return null;
        }
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.set(Calendar.HOUR_OF_DAY, 23);
        c.set(Calendar.SECOND, 59);
        c.set(Calendar.MINUTE, 59);
        return c.getTime();
    }

    public static String getToday(String pattern) {
        if (pattern == null) {
            pattern = YYYY_MM_DD;
        }
        return formatDate(new Date(), pattern);
    }

    public static String getTodayStartTime() {
        return getToday(null) + " 00:00:00";
    }

    public static String getTodayEndTime() {
        return getToday(null) + " 23:59:59";
    }
    /**
     * 时间比较(分钟)
     * @param startTime
     * @param endTime
     * @return long 时间差分钟
     * */
    public static long dateDiff(Date startTime,Date endTime){
        Calendar dateOne=Calendar.getInstance(),dateTwo=Calendar.getInstance();
        dateOne.setTime(startTime);	//设置为当前系统时间
        dateTwo.setTime(endTime);		//设置为2015年1月15日
        long timeOne=dateOne.getTimeInMillis();
        long timeTwo=dateTwo.getTimeInMillis();
        long minute=(timeOne-timeTwo)/(1000*60);//转化minute
        return minute;
    }
}
